package byteCode;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import java.util.concurrent.CountDownLatch;

/**
 * @author dengzhiyuan
 * @version 1.0
 * @describe
 * @time 2022/7/11 0:03
 */
public class CacheLinePadding {
    public static long COUNT = 100_000_000L;
    @sun.misc.Contended
    private static class Test {
        //private long p1, p2, p3, p4, p5, p6, p7;
        //8byte
        public volatile long x = 0L;
        //private long p9, p10, p11, p12, p13, p14, p15;
    }
    public static Test[] arr = new Test[2];

    static {
        arr[0] = new Test();
        arr[1] = new Test();
    }
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < COUNT; i++) {
                //volatile的缓存一致性协议MESI或者锁总线，会消耗时间
                arr[0].x = i;
            }
            latch.countDown();
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < COUNT; i++) {
                arr[1].x = i;
            }
            latch.countDown();
        });
        TimeInterval timer = DateUtil.timer();
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        latch.await();
        System.out.println("总计消耗时间：" + timer.interval());
    }
}
